/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.agtranscontinental.sisref.util;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author ericson
 */
public class ServiceLocator {

    private Logger LOG = Logger.getLogger(ServiceLocator.class.getName());
    HashMap serviceCache = null;
    InitialContext context = null;
    private static ServiceLocator serviceLocator = null;
    private Hashtable<String, Object> caching = new Hashtable<String, Object>(5);
    private static final String JNDI_BASE_ENTRY = "java:comp/env/ejb/";

    public ServiceLocator() {
        try {
            serviceCache = new HashMap();
            context = new InitialContext();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ServiceLocator getInstance() throws NamingException {
        if (serviceLocator == null) {
            serviceLocator = new ServiceLocator();
        }
        return serviceLocator;
    }

    public Object findService(String name) {
        try {
            Object objRef;
            if (null == (objRef = caching.get(name))) {
                InitialContext ic = new InitialContext();
                objRef = ic.lookup(JNDI_BASE_ENTRY + name);
                caching.put(name, objRef);
            }
            return objRef;
        } catch (NamingException e) {
            LOG.severe(e.getMessage());
        }
        return null;
    }

    public Object findServiceRemote(String name) {
        Object objRef = null;
        try {
            final Context context = getInitialContext();
            objRef = context.lookup("com.agtranscontinental.sisref.sessionremote." + name + "EjbRemote");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return objRef;
    }

    private Context getInitialContext() throws NamingException, ExceptionHandler {
        Hashtable env = new Hashtable();
        // Estableciendo el contexto inicial para GlassFish
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.appserv.naming.S1ASCtxFactory");
        env.put(Context.PROVIDER_URL, "iiop://localhost:3700");
        return new InitialContext(env);
    }
}
